//动态路由添加工具方法
import router from '@/router'
import { asyncRouters, basicRouters } from '@/router'
import Layout from '@/components/layout/Index.vue'

function toTreeArray(array, options) {
  const fn = (result, array, parentId, opts) => {
    let optChildren = opts.children
    let optData = opts.data
    let optClear = opts.clear
    let optKey = opts.key
    let optParentKey = opts.parentKey
    array.forEach((item) => {
      let children = item[optChildren]
      if (optData) {
        item = item[optData]
      }
      result.push({
        [optParentKey]: parentId,
        ...item,
      })
      if (children && children.length) {
        fn(result, children, item[optKey], opts)
      }
      if (optClear) {
        delete item[optChildren]
      }
    })
    return result
  }
  return fn([], array, null, {
    parentKey: 'parentId',
    key: 'id',
    children: 'children',
    ...options,
  })
}

//过滤出有权限路由
function filterRouter(menuList) {
  const filterMenuList = toTreeArray(menuList, {
    parentKey: 'parentId',
    key: 'menuId',
    children: 'list',
  })
  const menuSet = new Set(filterMenuList.map((el) => el.url))
  const accessRouters = asyncRouters.filter((routerItem) => menuSet.has(routerItem.path))
  return accessRouters
}

// 重置路由（移除所有动态添加的路由）
export function resetRouter() {
  const routes = router.getRoutes()
  const whiteList = basicRouters.map((el) => el.name)
  routes.forEach((route) => {
    if (route.name && !whiteList.includes(route.name)) {
      router.removeRoute(route.name)
    }
  })
}

// 添加基础布局路由
function addLayoutRoute() {
  if (!router.hasRoute('Layout')) {
    router.addRoute({
      path: '/',
      name: 'Layout',
      component: Layout,
      redirect: '/employeeInfo', //重定位到员工资料
      children: [], // 准备添加子路由
    })
  }
}

// 动态添加权限路由
export function addDynamicRoutes(menuList) {
  const accessRouters = filterRouter(menuList)
  resetRouter() // 先重置路由
  addLayoutRoute() // 确保Layout存在

  // 添加权限路由
  accessRouters.forEach((route) => {
    router.addRoute('Layout', route)
  })

  // 添加404路由
  router.addRoute({
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    redirect: '/404',
  })
  console.log(router.getRoutes(), '有权限路由list')
  return router.getRoutes()
}
